<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/11/17
 * Time: 19:04
 */

namespace backend\models;

use common\models\Package;
use common\models\PackageInitiation;
use common\models\PackageLog;
use common\models\PackageUpdateLog;
use common\models\Project;
use common\models\ProjectTeam;
use common\models\Responses;
use common\models\UserModel;
use yii\db\Exception;

class PackageInitiationPlan extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'package_initiation_plan';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'stage'], 'required'],
            [['package_id', 'lock_user'], 'integer'],
            [['job'], 'string'],
            [['created_at'], 'safe'],
            [['stage', 'lock_timestamp'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包',
            'stage' => '阶段',
            'job' => '结点',
            'created_at' => '创建时间',
            'lock_user' => '加锁用户',
            'lock_timestamp' => '加锁时间',
        ];
    }

    /*
     *  存储发起协同
     *  成功返回1，失败返回0
     */
    public static function setTeamMembersData($data, $workPlanData)
    {
        $userId = \Yii::$app->user->id;
        $changedAttributes = array();
        $initiationState = false;

        if (!empty($data['id'])) {
            $plan_model = PackageInitiation::findOne($data['id']);
        } else {
            $plan_model = new PackageInitiation();
        }
        if (empty($plan_model)) {
            $plan_model = new PackageInitiation();
        }
        if (isset($data['package_id'])) {
            if ($plan_model->id > 0 && $plan_model->package_id != $data['package_id']) {
                $changedAttributes['package_id'] = $data['package_id'];
                $initiationState = true;
            }
            $plan_model->package_id = $data['package_id'];
        }
        if (isset($data['pre_evaluation_id'])) {
            if ($plan_model->id > 0 && $plan_model->pre_evaluation != $data['pre_evaluation_id']) {
                $changedAttributes['pre_evaluation'] = $data['pre_evaluation_id'];
                $initiationState = true;
            }
            $plan_model->pre_evaluation = $data['pre_evaluation_id'];
        }
        if (isset($data['due_diligence_id'])) {
            if ($plan_model->id > 0 && $plan_model->due_diligence != $data['due_diligence_id']) {
                $changedAttributes['due_diligence'] = $data['due_diligence_id'];
                $initiationState = true;
            }
            $plan_model->due_diligence = $data['due_diligence_id'];
        }
        if (isset($data['leader_id'])) {
            if ($plan_model->id > 0 && $plan_model->leader != $data['leader_id']) {
                $changedAttributes['leader'] = $data['leader_id'];
                $initiationState = true;
            }
            $plan_model->leader = $data['leader_id'];
        }
        if (isset($data['zongjian_id'])) {
            if ($plan_model->id > 0 && $plan_model->leader != $data['zongjian_id']) {
                $changedAttributes['zongjian'] = $data['zongjian_id'];
                $initiationState = true;
            }
            $plan_model->zongjian = $data['zongjian_id'];
        }
        if (isset($data['other_team_notes'])) {
            if ($plan_model->id > 0 && $plan_model->other_team_notes != $data['other_team_notes']) {
                $changedAttributes['other_team_notes'] = $data['other_team_notes'];
                $initiationState = true;
            }
            $plan_model->other_team_notes = $data['other_team_notes'];
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if ($data['id'] > 0) {

//                var_dump($initiationState);
//                var_dump($data);
//                var_dump($plan_model);
//                print_r($changedAttributes);
//                exit();

                //TODO 添加团队组成记录
//                if ($initiationState) {
//                    $res = $plan_model->setUpdateLog($plan_model->id, $plan_model->package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_GROUP_USER, 2);
//                    if (!$res['state']) {
//                        throw new \Exception($res['msg']);
//                    }
//                }
                //查找资产包id是否存在
                $planData = $plan_model->save();
            } else {
                //查找资产包id是否存在
                $planData = $plan_model->save();
                //TODO 添加团队组成记录
//                $res = $plan_model->setUpdateLog($plan_model->id, $plan_model->package_id, $plan_model, $userId, PackageUpdateLog::MODULE_GROUP_USER, 1);
//                if (!$res['state']) {
//                    throw new \Exception($res['msg']);
//                }
            }

            //保存工作计划
            $workPlanState = self::setWorkPlanData($workPlanData['insertData'], $workPlanData['updateData'], 0);
            //更新状态
            $packageModel = Package::findOne($data['package_id']);
            if (!empty($packageModel) && $packageModel->state <= \Yii::$app->params['NONE']) {
                $packageModel->state = \Yii::$app->params['YUPINGGU'];
                $packageState = $packageModel->save(false);
                //TODO 添加资产包立项记录
//                if ($packageState) {
//                    $packageLog = new PackageLog();
//                    $packageLog->package_id = $packageModel->id;
//                    $packageLog->user_id = $userId;
//                    $realname = (new UserModel())->getRealname((int)$userId);
//                    $packageLog->log = $realname . '启动立项评估';
//                    $packageLog->created_at = date('Y-y-d H:i:s');
//                    if (!$packageLog->save()) {
//                        throw new \Exception('添加启动立项评估记录失败');
//                    }
//                }
            } else {
                $packageState = true;
            }
            //-----保存团队成员到项目team表中--fly--start--
            $projectModel = Project::findAll(['package_id'=>$data['package_id']]);
            if (!empty($packageModel)){
                    $partnerStr = trim($data['due_diligence_id'].$data['pre_evaluation_id'],',');
                    foreach ($projectModel as $k => $v){
                        $projectTeamModel = ProjectTeam::findOne(['project_id'=>$v['id']]);
                        if ($projectTeamModel != null) {
                            if (empty($projectTeamModel['partner'])){
                                $pTeamModel['partner']=$partnerStr;
                                $ptId = $projectTeamModel['id'];
                                \Yii::$app->db->createCommand()->update(ProjectTeam::tableName(), $pTeamModel, "id=$ptId")->execute();
                            }
                        }
                    }
                }
            //-----保存团队成员到项目team表中--fly--end--
            if ($planData && $workPlanState['code'] == 200 && $packageState) {
                $transaction->commit();
                return Responses::response200([], 1, "协同提交成功");
            }
            $transaction->rollBack();
            return Responses::response400('提交失败');
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('提交失败');
        }
    }

    /*
     * 查询项目包有没有发起过协同
     *  @$package_id :  包id
     *  @return  ：成功 [200,[99999,data]]
     *            ：失败 false
     */
    public static function getPackageState($package_id)
    {
        $connection = \Yii::$app->db;
        $sql = "SELECT state FROM package WHERE id = $package_id";
        try {
            if (!empty($package_id)) {
                $state = (new \yii\db\Query())->from('package')->where(['=','id',$package_id])->one();
                if (!$state) {
                    return false;
                }
                //获取已经发起的协同信息
                $sql1 = "SELECT id,pre_evaluation,due_diligence,other_team_notes,leader,zongjian FROM package_initiation   WHERE  package_id = $package_id";
                $sql2 = "SELECT id,job,stage FROM package_initiation_plan   WHERE package_id = $package_id";
                $Plandata1 = $connection->createCommand($sql1)->queryOne();
                $Plandata2 = $connection->createCommand($sql2)->queryAll();
                $Plandata3 = (new \yii\db\Query())->from('package as p')->leftJoin('user as u', 'p.owner = u.id')->leftJoin('auth_item as ai', 'ai.name = u.department')->where(['=', 'p.id', $package_id])->one();
                //通过id获取管理员名称
                $leaderIdArr = [];
                if (!empty($Plandata1['leader'])) {
                    $leaderIdArr = array_unique(explode(',', $Plandata1['leader']));
                }
                $leader_name = (new \yii\db\Query())->select('id,realname,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = department')->where(['in', 'id', $leaderIdArr])->all();
                $leader_name_str = self::pieceUsername($leader_name);
                //通过id获取管理员名称

                $leaderIdArr = [];
                if (!empty($Plandata1['leader'])) {
                    $leaderIdArr = array_unique(explode(',', $Plandata1['zongjian']));
                }
                $leader_name = (new \yii\db\Query())->select('id,realname,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = department')->where(['in', 'id', $leaderIdArr])->all();
                $zongjian_name_str = self::pieceUsername($leader_name);
                //通过id获取预评估人员名称
                $dueDiligenceIdArr = [];
                if (!empty($Plandata1['due_diligence'])) {
                    $dueDiligenceIdArr = array_unique(explode(',', $Plandata1['due_diligence']));
                }
                $due_diligence_name = (new \yii\db\Query())->select('id,realname,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['in', 'id', $dueDiligenceIdArr])->all();
                $due_diligence_name_str = self::pieceUsername($due_diligence_name);
                //通过id获取尽调成员
                $preEvaluationIdArr = [];
                if (!empty($Plandata1['pre_evaluation'])) {
                    $preEvaluationIdArr = array_unique(explode(',', $Plandata1['pre_evaluation']));
                }
                $pre_evaluation_name = (new \yii\db\Query())->select('id,realname,ai.description')->from(UserModel::tableName())->leftJoin('auth_item as ai', 'ai.name = user.department')->where(['in', 'id', $preEvaluationIdArr])->all();
                $pre_evaluation_name_str = self::pieceUsername($pre_evaluation_name);
                //T通过id获取上传人名称
                //组装数据
                $Plandata = [
                    'initiationPlan' => $Plandata2,
                    'workman' => [
                        'ownerId' => $Plandata3['owner'],
                        'ownerUserName' => $Plandata3['realname'],
                        'description' => $Plandata3['description'],
                        'id' => $Plandata1['id'],
                        'leader_id' => $Plandata1['leader'],
                        'zongjian_id' => $Plandata1['zongjian'],
                        'leader_name' => $leader_name_str,
                        'zongjian_name' => $zongjian_name_str,
                        'due_diligence_id' => $Plandata1['due_diligence'],
                        'due_diligence_name' => $due_diligence_name_str,
                        'pre_evaluation_id' => $Plandata1['pre_evaluation'],
                        'pre_evaluation_name' => $pre_evaluation_name_str,
                        'other_team_notes' => $Plandata1['other_team_notes']
                    ]
                ];
                if ($state['state']<=1) {
                    return Responses::response200($Plandata, 0); //99999表明已经发起过协同
                } else {
                    return Responses::response200($Plandata, 99999); //99999表明已经发起过协同
                }
            }else {
                return false;
            }
        }catch (\Exception $exception) {
            return false;
        }
    }

    /*
     * 保存协同-工作计划
     * @params ：$insertData 插入的数据
     * @params ：$updateData  更新的数据
     * @params ：$commitState  事物状态-同时操作多张表（在其他model中已经开启过事物不需要开启）
     * @return ：Responses::response200([],1,'更新并保存成功');
     */
    public static function setWorkPlanData($insertData, $updateData, $commitState = 1)
    {
        //分类数据id不等于0的是添加数据----id不等于0是一个数据
        $userId = \Yii::$app->user->id;
        $insertState = false;
        $updateState = false;
        if (empty($insertData) && empty($updateData)) {
            return Responses::response200();
        }
        if (!empty($insertData)) {
            if ($commitState) {
                $transaction = \Yii::$app->db->beginTransaction();
            }
            try {
                //$plankey = ['package_id', 'stage', 'job'];
                //$state = \Yii::$app->db->createCommand()->batchInsert(PackageInitiationPlan::tableName(), $plankey, $insertData)->execute();

                //----------------zhao shou qiang 添加修改日志 开始 -----------------
                $state = true;
            if (!empty($insertData) && is_array($insertData)) {
                    foreach ($insertData as $key => $value) {
                        $packageInitiationPlan = new PackageInitiationPlan();
                        $packageInitiationPlan->package_id = $value['package_id'];
                        $packageInitiationPlan->stage = $value['stage'];
                        $packageInitiationPlan->job = $value['job'];
                        $packageInitiationPlan->created_at = date('Y-m-d H:i:s', time());
                        if ($packageInitiationPlan->save()) {
                            $re = self::setLog($packageInitiationPlan->id, $packageInitiationPlan->package_id, $packageInitiationPlan, $userId, PackageUpdateLog::MODULE_WORK_PLAN, 1); // $userId, PackageUpdateLog::MODULE_WORK_PLAN, 1
                            if (!$re['state']) {
                                $state = false;
                                throw new \Exception($re['msg']);
                            }
                        } else {
                            $state = false;
                            throw new \Exception('添加工作计划失败');
                            continue;
                        }
                    }
                }
                //----------------zhao shou qiang 添加修改日志 结束-----------------

                if ($commitState && $state) {
                    $transaction->commit();
                }
                $insertState = true;
            } catch (\Exception $exception) {
                if ($commitState) {
                    $transaction->rollBack();
                }
                $insertState = false;
            }
        }

        if (!empty($updateData)) {
            if ($commitState) {
                $transaction = \Yii::$app->db->beginTransaction();
            }
            try {
                //----------------zhao shou qiang 添加修改日志 开始 -----------------
                if (!empty($updateData) && is_array($insertData)) {
                    foreach ($updateData as $key => $value) {
                        $changedAttributes = array();
                        $packageInitiationPlan = PackageInitiationPlan::findOne((int)$value['id']);
                        if ($packageInitiationPlan === null) {
                            continue;
                            throw new \Exception('该数据不存在');
                        }

                        if ($packageInitiationPlan->package_id != $value['package_id']) {
                            $changedAttributes['package_id'] = $value['package_id'];
                        }

                        if ($packageInitiationPlan->stage != $value['stage']) {
                            $changedAttributes['stage'] = $value['stage'];
                        }

                        if ($packageInitiationPlan->job != $value['job']) {
                            $changedAttributes['job'] = $value['job'];
                        }

                        if (!empty($changedAttributes)) {
                            $re = self::setLog($packageInitiationPlan->id, $packageInitiationPlan->package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_WORK_PLAN, 2);
                            if (!$re['state']) {
                                throw new \Exception($re['msg']);
                            }
                        }
                    }
                }
                //----------------zhao shou qiang 添加修改日志 结束 -----------------

//*批量多条不同条件的不同值，效率低*/
//                $sql = 'UPDATE package_initiation_plan SET stage = CASE id';
//                foreach ($updateData as $k => $v) {
//                    $sql .= sprintf(" WHEN %d THEN %d ", $v['id'], $v['stage']);
//                }
//                $sql .= "END,  job = CASE id";
//                foreach ($updateData as $k => $v) {
//                    $sql .= sprintf(" WHEN %d THEN %d ", $v['id'], $v['job']);
//                }
//                $ids = '';
//                foreach ($updateData as $k => $v) {
//                    $ids.=$v['id'].',';
//                }
//                $ids = substr($ids,0,strlen($ids)-1);
//                $sql .= "END WHERE id IN ($ids)";
//                echo $sql;die;
                $sql = 'replace into package_initiation_plan (id,job,stage,package_id) values';
                $sql1 = '';
                foreach ($updateData as $k => $v) {
//                    $sql.="(".$v['id'].','.\"$v['job']\".','.$v['stage']."),";
                    $id = $v['id'];
                    $job = $v['job'];
                    $stage = $v['stage'];
                    $package_id = $v['package_id'];
                    $sql1 .= <<<SQL
                  ($id,"$job","$stage",$package_id),
SQL;
                }
                $sql .= $sql1;
                $sql = substr($sql, 0, strlen($sql) - 1);
                $Plandata1 = \Yii::$app->getDb()->createCommand($sql)->execute();
                if ($Plandata1 && $commitState) {
                    $transaction->commit();
                    $updateState = true;
                }
                $updateState = false;
            } catch (\Exception $exception) {
                if ($commitState) {
                    $transaction->rollBack();
                }
                $updateState = false;
                return Responses::response400('更新失败');
            }
        }
        if ($updateState && $insertState) {
            return Responses::response200([], 1, '更新并保存成功');
        }
        if ($updateState) {
            return Responses::response200([], 1, '更新成功');
        }
        if ($insertState) {
            return Responses::response200([], 1, '保存成功');
        }
        return Responses::response200([], 1, '无更新');
    }

    /*
     * 删除协同-工作计划
     */
    public static function delWorkPlanData($id)
    {
        if (empty($id)) {
            return Responses::response400('删除失败');
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {

            //--------------- zhao shou qiang 添加删除记录 开始 ----------------
            $model = self::findOne((int)$id);
            if ($model === null) {
                throw new Exception('数据不存在');
            }
            $res = self::setLog($id, $model->package_id, array(), \Yii::$app->user->id, PackageUpdateLog::MODULE_WORK_PLAN, 3);
            if (!$res['state']) {
                throw new \Exception($res['msg']);
            }
            //--------------- zhao shou qiang 添加删除记录 结束 ----------------

            $sql = "delete from package_initiation_plan where id = " . $id;
            $delState = \Yii::$app->getDb()->createCommand($sql)->execute();
            if ($delState) {
                $transaction->commit();
                return Responses::response200([], 1, '删除成功');
            } else {
                $transaction->rollBack();
                return Responses::response400('删除失败');
            }
        } catch (\Exception $exception) {
            $transaction->rollBack();
            return Responses::response400('删除失败');
        }
    }

    /*
     * 根据查询的realname 进行拼装
     * 小明,小红
     */
    public static function pieceUsername($leader_name)
    {
        $leader_name_str = [];
        foreach ($leader_name as $k => $v) {
            $leader_name_str[$k]['id'] = $v['id'];
            $leader_name_str[$k]['text'] = $v['realname'];
            $leader_name_str[$k]['description'] = $v['description'];
        }
        return $leader_name_str;
    }

    /*
     *获取工作人员的id
     * $group 区分是否多选
     * return string
     */
    public static function getUserId($usernameArr,$group=1)
    {
        if (!empty($usernameArr)){
            $where_param = ['or', ['realname'=>$usernameArr]];
        }else{
            $where_param = ['=','id',-1];
        }
        $data['userId'] = (new \yii\db\Query())->select('id')->from(UserModel::tableName())->where($where_param)->all();
        if (!empty($data['userId'])) {
            if ($group==0){
                $data['count'] = count($data['userId']);
                $data['userIdString'] = '';
                foreach ($data['userId'] as $k => $v) {
                    $data['userIdString'] = $data['userIdString'] . ',' . $v['id'];
                }
                $data['userIdString'] .= ',';
                return $data['userIdString'];
            }else{
                return $data['userId'][0]['id'];
            }
        }
        return [];
    }

    /**
     * 工作计划列表
     * @param array $where
     * @return array
     */
    public static function getList($where = array())
    {
        $list = (new \yii\db\Query())->select([])
            ->from(self::tableName())
            ->where($where)
            ->indexBy('id')
            ->all();
        return $list;
    }


    /**
     * 更新记录
     * @param $id 主键
     * @param $package_id 资产包id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 资类包修改日志module
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public static function setLog($id, $package_id, $changedAttributes, $userId, $module, $type)
    {
        $model = self::findOne((int)$id);
        $package = Package::findOne($package_id);
        if ($model === null || $package === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }
        $attributeLabels = (new PackageInitiationPlan())->attributeLabels();
        $intAttributeLabels = ['package_id', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList(['user.id' => $userId]);
        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的工作计划数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
        }

        try {
            $time = date('Y-m-d H:i:s');
            $packageUpdateLog = new PackageUpdateLog();
            $module_title_array = $packageUpdateLog->getModuleArrayTitle();
            $packageUpdateLog->package_id = $package_id;
            $packageUpdateLog->module = $module_title_array[$module];
            $packageUpdateLog->created_at = $time;
            $packageUpdateLog->user_id = $userId;
            $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');

            $re1 = $packageUpdateLog->save();
            if (!$re1) {
                throw new Exception('资产包工作计划记录添加失败');
            }

            return array('state' => true, 'msg' => '添加工作计划记录成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }
}